我們要建立藍牙我們需要多寫一個Swift,因為這樣我們在呼叫的時候就不會覺得,畫面非常的亂,我們將藍芽設定完後
var central: CBCentralManager?
我們將程式設為副線程,並且將代理指派給自己
let queue = DispatchQueue.global()
central = CBCentralManager(delegate: self, queue: queue)
讓我們將掃描的程式打上去
central?.scanForPeripherals(withServices: nil, options: nil)
如果我們要停止掃描的話我們要用
central?.stopScan()
當程式開始運作我們就能夠看到附近的藍芽掃描出來了,下期我們再來教如何將掃描出來的藍芽顯示出來
我們通常會寫一個extension
extension BluetoothServices: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown:
print("unknown")
case .resetting:
print("resetting")
case .unsupported:
print("unsupported")
case .unauthorized:
print("unauthorized")
case .poweredOff:
print("poweredOff")
case .poweredOn:
print("poweredOn")
@unknown default:
print("藍芽裝置未知狀態")
}
startScan()
}
/// 發現裝置
func centralManager(_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData: [String : Any],
rssi RSSI: NSNumber) {
for newPeripheral in blePeripherals {
if peripheral.name == newPeripheral.name {
return
}
}
if let name = peripheral.name {
blePeripherals.append(peripheral)
print(name)
}
delegate?.getBLEPeripherals(peripherals: blePeripherals)
}
/// 連接裝置
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices(nil)
}
}
這樣我們就可以把裝置名稱放到name裏面